//
//  FactoryDetailViewController.m
//  Rail
//
//  Created by hychen on 2018/3/4.
//  Copyright © 2018年 Hychen. All rights reserved.
//

#import "FactoryDetailViewController.h"
#import "FactoryDetailTableViewCell.h"
#import "ObserverTableViewCell.h"
#import "FactorySectionView.h"
#import "LineDetailDescTableViewCell.h"
#import "WorkAreaDetailModel.h"
#import "BMItemView.h"
#import "ErrorView.h"

#import "MemberStatisticViewController.h"
#import "DeviceStatisticViewController.h"
#import "EnvironmentObserverViewController.h"
#import "FactoryObserverDeviceViewController.h"


@interface FactoryDetailViewController ()
@property (nonatomic, strong) UIButton *collectionButton;
@property (nonatomic, strong) WorkAreaDetailModel *detailModel;
@property (nonatomic, strong) WorkAreaStatisticModel *statisticModel;
@property (nonatomic, strong) NSArray *secTwoArray;
@property (nonatomic, strong) NSArray *secThreeArray;
@property (nonatomic, strong) NSArray *secFourArray;
@property (nonatomic, strong) NSArray *secFiveArray;
@property (nonatomic, strong) ErrorView *errorView;

@property (nonatomic, assign) BOOL isLoading;
@end

@implementation FactoryDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self.view insertSubview:self.errorView belowSubview:self.tableView];
    [self.errorView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    
    [self.navigationItem addSimpleTitleView:@"某工区"];
    
    self.collectionButton = [self.navigationItem addRightNavItem:self normalImage:[UIImage imageNamed:@"app_title_bar_back_n_ic"] highlightedImage:[UIImage imageNamed:@"app_title_bar_back_p_ic"] selector:@selector(clickCollectionButton:)];
    [self.collectionButton setImage:[UIImage imageNamed:@"app_title_bar_back_n_ic"] forState:UIControlStateNormal];
    [self.collectionButton setImage:[UIImage imageNamed:@"app_title_bar_back_p_ic"] forState:UIControlStateSelected];
    
    [self.tableView.mj_header beginRefreshing];
}

- (void)setNavTitle:(NSString *)navTitle {
    _navTitle = navTitle;
    [self.navigationItem addSimpleTitleView:navTitle];
}

- (void)clickCollectionButton:(UIButton *)button {
    BOOL isFav = button.selected;
    if (isFav) {
        [self cancelFactoryCollection];
    }
    else {
        [self addFactoryCollection];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)refreshData {
    _factoryRequestDataDone = 0;
    BMWeakSelf
    //工区详情
    [HttpRequest loadFactoryDetailDataWithAreaId:self.areaid?:@"" success:^(WorkAreaDetailModel *object) {
        weakSelf.detailModel = object;
        weakSelf.collectionButton.selected = weakSelf.detailModel.is_fav;
        weakSelf.factoryRequestDataDone = FactoryRequestTypeFactoryDetail;
        [weakSelf.navigationItem addSimpleTitleView:object.area_name?:@"某工区"];
    } failure:^(NSString *code, NSString *msg) {
        if ([code isEqualToString:@"1003"]) {
            //显示无权限图片
            [weakSelf.view bringSubviewToFront:weakSelf.errorView];
            [weakSelf.errorView setImage:nil title:@"没有权限查询该工区信息"];
            weakSelf.collectionButton.hidden = YES;
        }
        Show_Msg_Error(msg)
        weakSelf.factoryRequestDataDone = FactoryRequestTypeFactoryDetail;
    }];
    
    //工区统计数据
    [HttpRequest loadFactoryStatisticDataWithAreaId:self.areaid?:@"" success:^(WorkAreaStatisticModel *object) {
        weakSelf.statisticModel = object;
        weakSelf.factoryRequestDataDone = FactoryRequestTypeFactoryStatistic;
    } failure:^(NSString *code, NSString *msg) {
        Show_Msg_Error(msg)
        weakSelf.factoryRequestDataDone = FactoryRequestTypeFactoryStatistic;
    }];
}

- (void)addFactoryCollection {
    if (self.isLoading) {
        return;
    }
    if (self.detailModel.is_fav) {
        return;
    }
    self.isLoading = YES;
    Show_Msg(@"收藏中")
    BMWeakSelf
    [HttpRequest addFavWithLineId:@"" areaId:self.detailModel.areaid?:@"" deviceId:@"" success:^(id object) {
        weakSelf.collectionButton.selected = YES;
        weakSelf.detailModel.favid = object;
        Show_Msg_Success(@"收藏成功")
        weakSelf.isLoading = NO;
    } failure:^(NSString *code, NSString *msg) {
        Show_Msg_Error(msg)
        weakSelf.isLoading = NO;
    }];
}

- (void)cancelFactoryCollection {
    if (self.isLoading) {
        return;
    }
    self.isLoading = YES;
    Show_Msg(@"取消收藏中")
    BMWeakSelf
    [HttpRequest cancelFavWithFavId:self.detailModel.favid?:@"" success:^(id object) {
        weakSelf.detailModel.favid = nil;
        weakSelf.collectionButton.selected = NO;
        Show_Msg_Success(@"取消收藏成功")
        weakSelf.isLoading = NO;
    } failure:^(NSString *code, NSString *msg) {
        Show_Msg_Error(msg)
        weakSelf.isLoading = NO;
    }];
}

- (void)setFactoryRequestDataDone:(FactoryRequestType)factoryRequestDataDone {
    _factoryRequestDataDone = _factoryRequestDataDone | factoryRequestDataDone;
    if (_factoryRequestDataDone == FactoryRequestTypeFactoryAll) {
        [self setupData];
        [self.tableView.mj_header endRefreshing];
        [self.tableView reloadData];
        _factoryRequestDataDone = 0;
    }
}

- (void)setupData {

    //设备统计
    NSArray *secTwoArray = [BMItemModel mj_objectArrayWithKeyValuesArray:
                      
                            @[@{@"title":@"门禁",@"content":[NSString stringWithFormat:@"%@/%@",self.statisticModel.rke_count_online?:@"",self.statisticModel.rke_count?:@""]},
                        @{@"title":@"对讲",@"content":[NSString stringWithFormat:@"%@/%@",self.statisticModel.tbk_count_online?:@"",self.statisticModel.tbk_count?:@""]},
                        @{@"title":@"广播",@"content":[NSString stringWithFormat:@"%@/%@",self.statisticModel.broadcast_count_online?:@"",self.statisticModel.broadcast_count?:@""]},
                        @{@"title":@"定位",@"content":[NSString stringWithFormat:@"%@/%@",self.statisticModel.helmet_count_online?:@"",self.statisticModel.helmet_count?:@""]},
                        @{@"title":@"环境",@"content":[NSString stringWithFormat:@"%@/%@",self.statisticModel.env_count_online?:@"",self.statisticModel.env_count?:@""]},
                        @{@"title":@"重型",@"content":[NSString stringWithFormat:@"%@/%@",self.statisticModel.he_count_online?:@"",self.statisticModel.he_count?:@""]},]
                      ];
    
    //人员统计
    NSArray *secThreeArray = [BMItemModel mj_objectArrayWithKeyValuesArray:
                              
                              @[@{@"title":@"在线",@"content":self.statisticModel.online_count?:@"0"},
                                @{@"title":@"施工",@"content":self.statisticModel.workuser_count?:@"0"},
                                @{@"title":@"监理",@"content":self.statisticModel.supervisor_count?:@"0"},
                                @{@"title":@"管理",@"content":self.statisticModel.manger_count?:@"0"},
                                @{@"title":@"业主",@"content":self.statisticModel.owner_count?:@"0"},
                                @{@"title":@"其他",@"content":self.statisticModel.other_count?:@"0"},]
                                ];
    //环境监测
    NSString *wetness = [self.statisticModel.wetness objectIsNotEmpty] ? [NSString stringWithFormat:@"%@%%",self.statisticModel.wetness?:@""] : @"-";
    NSString *temperature = [self.statisticModel.temperature objectIsNotEmpty] ? [NSString stringWithFormat:@"%@℃",self.statisticModel.temperature?:@""] : @"-";
    NSString *pm = [self.statisticModel.pm objectIsNotEmpty] ? [NSString stringWithFormat:@"%@μg/m3",self.statisticModel.pm?:@""] : @"-";
    NSString *noise = [self.statisticModel.noise objectIsNotEmpty] ? [NSString stringWithFormat:@"%@db",self.statisticModel.noise?:@""] : @"-";
    NSArray *secFourArray = [BMItemModel mj_objectArrayWithKeyValuesArray:
                             @[@{@"title":@"湿度",@"content":wetness},
                               @{@"title":@"温度",@"content":temperature},
                            @{@"title":@"PM2.5",@"content":pm},
                               @{@"title":@"噪音",@"content":noise},
                               ]
                             ];
    //工区信息
    NSArray *secFiveArray = [BMItemModel mj_objectArrayWithKeyValuesArray:
                             
                             @[@{@"title":@"所属标段",@"content":self.detailModel.section_name?:@""},
                               @{@"title":@"所属线路",@"content":self.detailModel.line_name?:@""},
                               @{@"title":@"施工单位",@"content":self.detailModel.work_sp_name?:@""},
                               @{@"title":@"监理单位",@"content":self.detailModel.supervisor_sp_name?:@""},
                               @{@"title":@"第三方单位",@"content":self.detailModel.project_sp_name?:@""},
                               @{@"title":@"操作人",@"content":self.detailModel.op_name?:@""},
                               ]
                             ];
    
    self.secTwoArray = secTwoArray;
    self.secThreeArray = secThreeArray;
    self.secFourArray = secFourArray;
    self.secFiveArray = secFiveArray;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 5;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 1;
    }
    else if (section == 1) {
        return 1;
    }
    else if (section == 2) {
        return 1;
    }
    else if (section == 3) {
        return 1;
    }
    else if (section == 4) {
        return self.secFiveArray.count;
    }
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        ObserverTableViewCell *cell = [ObserverTableViewCell cellWithTableView:tableView class:[ObserverTableViewCell class]];
        [cell setAllObserverNum:self.detailModel.ipcam_count?:@"0" onlineObserverNum:self.detailModel.ipcam_count_online?:@"0"];
        BMWeakSelf
        [cell setBlockClickAllObserver:^{
            [weakSelf gotoAllObserverObserverVc];
        }];
        [cell setBlockClickOnlineObserver:^{
            [weakSelf gotoOnlineObserverObserverVc];
        }];
        return cell;
    }
    else if (indexPath.section == 1) {
        FactoryDetailTableViewCell *cell = [FactoryDetailTableViewCell cellWithInitStyleTableView:tableView class:[FactoryDetailTableViewCell class]];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.dataArray = self.secTwoArray;
        BMWeakSelf
        [cell setBlockClickItem:^(BMItemModel *model, NSInteger index) {
            [weakSelf gotoDeviceStatisticVcWithType:index];
        }];
        return cell;
    }
    else if (indexPath.section == 2) {
        FactoryDetailTableViewCell *cell = [FactoryDetailTableViewCell cellWithInitStyleTableView:tableView class:[FactoryDetailTableViewCell class]];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.dataArray = self.secThreeArray;
        BMWeakSelf
        [cell setBlockClickItem:^(BMItemModel *model, NSInteger index) {
            [weakSelf gotoMemberStatisticVcWithType:index];
        }];
        return cell;
    }
    else if (indexPath.section == 3) {
        FactoryDetailTableViewCell *cell = [FactoryDetailTableViewCell cellWithInitStyleTableView:tableView class:[FactoryDetailTableViewCell class]];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.dataArray = self.secFourArray;
        return cell;
    }
    else if (indexPath.section == 4) {
        LineDetailDescTableViewCell *cell = [LineDetailDescTableViewCell cellWithTableView:tableView class:[LineDetailDescTableViewCell class]];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        //
        BMItemModel *model = [self.secFiveArray objectAtIndex:indexPath.row];
        cell.model = model;
        return cell;
    }
    return [UITableViewCell new];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return 100;
    }
    else if (indexPath.section == 1) {
        return 60;
    }
    else if (indexPath.section == 2) {
        return 60;
    }
    else if (indexPath.section == 3) {
        return 60;
    }
    else if (indexPath.section == 4) {
        return 48;
    }
    return 0;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (section > 0) {
        FactorySectionView *view = [FactorySectionView sectionView];
        if (section == 1 || section == 2 || section == 3) {
            view.canClick = YES;
            BMWeakSelf
            [view setBlockClick:^(NSInteger section) {
                if (section == 1) {
                    [weakSelf gotoDeviceStatisticVcWithType:DeviceStatisticTypeRke];
                }
                else if (section == 2) {
                    [weakSelf gotoMemberStatisticVcWithType:MemberStatisticTypeAll];
                }
                else if (section == 3) {
                    [weakSelf gotoEnviromentObserverVc];
                }
            }];
        }
        view.section = section;
        
        if (section == 1) {
            view.titleLabel.text = @"设备统计";
            view.contentLabel.text = @"(在线/总数)";
        }
        else if (section == 2) {
            view.titleLabel.text = @"人员统计";
        }
        else if (section == 3) {
            view.titleLabel.text = @"环境监测";
        }
        else if (section == 4) {
            view.titleLabel.text = @"工区信息";
            view.arrowImage.hidden = YES;
        }
        return view;
    }
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section > 0) {
        return 50.f;
    }
    return 0;
}

- (void)gotoDeviceStatisticVcWithType:(DeviceStatisticType)type {
    DeviceStatisticViewController *vc = [[DeviceStatisticViewController alloc] initWithType:type];
    vc.areaId = self.areaid?:@"";
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)gotoMemberStatisticVcWithType:(MemberStatisticType)type {
    MemberStatisticViewController *vc = [[MemberStatisticViewController alloc] initWithType:type];
    vc.areaId = self.areaid?:@"";
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)gotoEnviromentObserverVc {
    EnvironmentObserverViewController *vc = [EnvironmentObserverViewController new];
    vc.detailModel = self.detailModel;
    vc.statisticModel = self.statisticModel;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)gotoAllObserverObserverVc {
    FactoryObserverDeviceViewController *vc = [FactoryObserverDeviceViewController new];
    vc.lineId = self.detailModel.lineid;
    vc.stationId = self.detailModel.stationid;
    vc.areaId = self.areaid;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)gotoOnlineObserverObserverVc {
    FactoryObserverDeviceViewController *vc = [FactoryObserverDeviceViewController new];
    vc.lineId = self.detailModel.lineid;
    vc.stationId = self.detailModel.stationid;
    vc.areaId = self.areaid;
    vc.isOnline = YES;
    [self.navigationController pushViewController:vc animated:YES];
}

- (ErrorView *)errorView {
    if (!_errorView) {
        _errorView = [ErrorView new];
    }
    return _errorView;
}
@end
